<template>
  <x-sub-page :isFixBtn="true">
    <div class="enquiry-detail" v-loading="pageLoading">
      <div class="form-components">
        <div class="panl-title">
          <span>基础信息</span>
        </div>
      </div>
      <el-descriptions
        direction="vertical"
        :column="4"
        label-class-name="title-style"
        content-class-name="content-style"
      >
        <el-descriptions-item label="询价单号">{{ dataForm.number | emptyVal }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{
          selectDictLabel(dictOptions['srm_enquiry.state'], dataForm.state) | emptyVal
        }}</el-descriptions-item>
        <el-descriptions-item label="询价单标题">{{ dataForm.title | emptyVal }}</el-descriptions-item>
        <el-descriptions-item label="采购组织">{{ dataForm.purchaseOrg | emptyVal }}</el-descriptions-item>
        <el-descriptions-item label="采购组">{{ dataForm.purchaseTeam | emptyVal }}</el-descriptions-item>
        <el-descriptions-item label="货币">{{
          selectDictLabel(dictOptions['currency'], dataForm.currency) | emptyVal
        }}</el-descriptions-item>
        <el-descriptions-item label="发票要求">{{
          selectDictLabel(dictOptions['srm_enquiry.invoice_type'], dataForm.invoiceType) | emptyVal
        }}</el-descriptions-item>
        <el-descriptions-item label="付款条件">{{
          selectDictLabel(dictOptions['payment_terms'], dataForm.paymentTerms) | emptyVal
        }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ dataForm.createName | emptyVal }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ dataForm.createTime | emptyVal }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        direction="vertical"
        :column="1"
        label-class-name="title-style"
        content-class-name="content-style"
      >
        <el-descriptions-item label="申请说明"> {{ dataForm.remark | emptyVal }} </el-descriptions-item>
      </el-descriptions>
      <div class="form-components">
        <div class="panl-title">
          <span>询价规则</span>
        </div>
      </div>
      <el-descriptions
        direction="vertical"
        :column="4"
        label-class-name="title-style"
        content-class-name="content-style"
      >
        <el-descriptions-item label="报价结束时间">{{ dataForm.endDate | emptyVal }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        direction="vertical"
        :column="1"
        label-class-name="title-style"
        content-class-name="content-style"
      >
        <el-descriptions-item label="询价要求"> {{ dataForm.demand | emptyVal }} </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        direction="vertical"
        :column="1"
        label-class-name="title-style"
        content-class-name="content-style"
      >
        <el-descriptions-item label="询价文件">
          <x-upload
            ref="fileUpload"
            :edit-flag="false"
            :limit="9"
            :fileSize="30"
            :span="6"
            :isFileRemark="false"
            :old-file-list="dataForm.srmEnquiryFileList"
            :tips="'最多上传9张，附件大小不超过30MB.'"
          >
          </x-upload>
        </el-descriptions-item>
      </el-descriptions>
      <div class="form-components">
        <div class="panl-title">
          <span>询价物料清单</span>
        </div>
      </div>
      <el-form ref="dataForm" :model="dataForm" :rules="dataRule" style="padding-bottom: 60px">
        <x-table
          ref="tableCom"
          :isPagination="false"
          :data-source="dataForm.srmEnquiryDetailList"
          :row-key="'id'"
          :height="getTableHeight(dataForm.srmEnquiryDetailList)"
        >
          <el-table-column
            v-for="(item, index) in enquiryMaterialColumns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width"
            :min-width="item.minWidth || '-'"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <span v-if="item.prop === 'materialUnit'">
                {{ selectDictLabel(dictOptions['srm_material.material_unit'], scope.row[item.prop]) }}</span
              >
              <span v-else-if="item.prop === 'deliveryDate'">{{ replaceDateTime(scope.row[item.prop]) }}</span>
              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="报价单价(含税)/元" min-width="160">
            <div class="item" slot-scope="scope">
              <el-form-item
                :prop="`srmEnquiryDetailList.${scope.$index}.${['unitPrice']}`"
                :rules="dataRule['unitPrice']"
              >
                <el-input-number v-if="quoteSign" v-model="scope.row.unitPrice"  :controls="false" :precision="2" clearable placeholder="请输入" size="mini" style="width: 100%"></el-input-number>
                <span v-else>{{ scope.row.unitPrice }}</span>
              </el-form-item>
            </div>
          </el-table-column>
          <el-table-column prop="totalPrice" label="总价(含税)" min-width="100"></el-table-column>
          <el-table-column prop="remark" label="备注" min-width="180"></el-table-column>
        </x-table>
      </el-form>
    </div>
    <fixed-btn-area>
      <el-button @click="handleBack"> {{ '返回' }} </el-button>
      <el-button
        v-if="quoteSign"
        v-hasPermi="['source:enquiry:quote']"
        type="primary"
        @click="handleSubmit"
        :loading="pageLoading"
      >
        {{ '报价' }}
      </el-button>
    </fixed-btn-area>
  </x-sub-page>
</template>

<script>
import {
  PermissionsMixin,
  QueryDictMixin,
  cloneDeep,
  selectDictLabel,
  multiply,
  throttle,
  checkTwoFloatNumber,
  replaceDateTime
} from '@package/utils'
import { apiGetEnquiryDetail, apiPostQuote } from '@/modules/searchSource/api/enquiry.js'
import { enquiryMaterialColumns, enquirySupplierColumns } from '@/modules/searchSource/config/enquiry.js'
import { EnumApiCode } from '../../../../../../globalEnum.js'

export default {
  name: 'EnquiryDetail',
  mixins: [PermissionsMixin, QueryDictMixin],
  inject: ['closePages'],
  data() {
    return {
      pageLoading: false,
      enquiryId: '',
      quoteSign: false, // 报价标记 为true的时候可以报价
      enquiryMaterialColumns,
      enquirySupplierColumns,
      srmDictKeys: [
        'srm_enquiry.state',
        'currency',
        'srm_enquiry.invoice_type',
        'payment_terms',
        'srm_material.material_unit'
      ],
      dataForm: {
        title: '',
        realName: '',
        mobile: '',
        remark: '',
        type: '',
        srmEnquiryDetailList: []
      },
      dataRule: {
        unitPrice: [
          { required: true, message: '请输入报价', trigger: ['blur'] },
          { validator: this.validateMoney, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {
    'dataForm.srmEnquiryDetailList': {
      handler(list) {
        list &&
          list.forEach((item) => {
            item.totalPrice = multiply(item.unitPrice, item.quantity)
          })
      },
      immediate: false,
      deep: true
    }
  },
  mounted() {
    const {
      query: { id, quoteSign }
    } = this.$route
    this.quoteSign = quoteSign
    this.enquiryId = id
    this.getInfo(id)
    this.initDictConfig()
  },
  methods: {
    selectDictLabel,
    replaceDateTime,
    getTableHeight(arr) {
      return (arr?.length || 1) * 64 + 80 || 200
    },
    validateMoney(rule, value, callback) {
      if (value && value !== '' && !checkTwoFloatNumber(value)) {
        callback(new Error('最多两位小数的数字'))
      } else {
        callback()
      }
    },
    // 获取详情
    async getInfo(id) {
      this.pageLoading = true
      const { data, code } = await apiGetEnquiryDetail(id)
      this.pageLoading = false
      if (code === EnumApiCode.Success) {
        this.$nextTick(() => {
          this.dataForm = Object.assign(this.dataForm, cloneDeep(data))
        })
      }
    },
    handleSubmit: throttle(function () {
      this.$refs.dataForm.validate(async (valid) => {
        if (valid) {
          this.pageLoading = true
          const enquiryQuoteDtoList = this.dataForm.srmEnquiryDetailList.map((item) => {
            return {
              enquiryDetailId: item.enquiryDetailId,
              materialCode: item.materialCode,
              unitPrice: item.unitPrice,
              totalPrice: item.totalPrice,
              remark: item.remark
            }
          })
          const param = {
            enquiryId: this.enquiryId,
            enquiryQuoteDtoList
          }
          try {
            const { code, msg } = await apiPostQuote(param)
            this.pageLoading = false
            if (code === EnumApiCode.Success) {
              this.$message.success('提交报价成功')
              this.handleBack()
            } else {
              this.$message.error(msg)
            }
          } finally {
            this.pageLoading = false
          }
        } else {
          this.$message.error('请检查询价物料清单报价信息是否填写完善')
          return false
        }
      })
    }, 1000),
    handleBack() {
      this.$router.go(-1)
      this.closePages()
    }
  }
}
</script>

<style lang="scss" scoped>
.enquiry-detail {
  padding: 0 20px;
  overflow: auto;
  .panl-title {
    height: 45px;
    // margin: 0 16px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ededed;
    margin-bottom: 16px;
    span {
      display: inline-block;
      height: 22px;
      line-height: 22px;
      color: #171c26;
      border-left: 2px solid #4474f6;
      padding-left: 12px;
      font-size: 16px;
      font-weight: 700;
    }
  }
  ::v-deep .title-style {
    color: #707683;
    font-size: 14px;
  }
  ::v-deep .content-style {
    padding-bottom: 20px;
    color: #333;
    font-size: 14px;
  }
  .table-title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    color: #707683;
    font-weight: normal;
  }
  ::v-deep .el-table .el-table__body tr {
    height: 56px;
  }
  ::v-deep .el-table .cell {
    line-height: 56px;
    height: 56px;
    display: flex;
    align-items: center;
  }
  ::v-deep .el-table__row .el-form-item {
    margin-bottom: 0;
  }
  ::v-deep .el-table__row .el-form-item__error {
    padding-top: 0;
  }
  ::v-deep .el-table__row .el-form-item__content {
    line-height: 32px;
  }
  ::v-deep .el-table__fixed::before {
    background: none;
  }
  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
}
</style>
